package com.naiterui.ehp.bs.weixin.subscribe;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 基础订阅通知参数
 *
 * @author zhoupeipei
 * @date 2019-06-19 15:11
 * @since 1.0.0
 */
@Data
public abstract class BaseSubscribe implements Serializable {
    private static final long serialVersionUID = -7092042601178705963L;
    private static final Pattern PATTERN = Pattern.compile("(\\<[^\\>]*\\>)");
    /**
     * 目标用户openID
     */
    private String openId;
    /**
     * 跳转页面全路径
     */
    private String targetPage;

    /**
     * 模板标识，用于匹配具体通知的模板配置。由每个子类指定
     *
     * @return
     */
    public abstract String getTemplateLabel();

    /**
     * 格式化文本参数信息
     *
     * @param contentList
     */
    public abstract void handleContent(List<SubscribeProperties.Content> contentList);

    /**
     * 非空参数校验
     *
     * @return
     */
    public boolean validate() {
        return StringUtils.isNotBlank(openId) ? true : false;
    }

    /**
     * 根据用户信息格式化模板消息内容
     *
     * @param contentList
     * @param formatMap
     */
    protected void formatData(List<SubscribeProperties.Content> contentList, Map<String, String> formatMap) {
        for (SubscribeProperties.Content dt : contentList) {
            String value = dt.getValue();
            List<String> formatKeys = extractStrByRegular(value);
            //格式化字符串
            for (String key : formatKeys) {
                String formatValue = formatMap.get(key);
                value = value.replace("<" + key + ">", formatValue);
            }
            dt.setValue(value);
        }
    }

    /**
     * 使用正则表达式提取中括号中的内容
     *
     * @param value
     *
     * @return
     */
    private List<String> extractStrByRegular(String value) {
        List<String> list = new ArrayList();
        if (StringUtils.isBlank(value)) {
            return list;
        }
        Matcher m = PATTERN.matcher(value);
        while (m.find()) {
            list.add(m.group().substring(1, m.group().length() - 1));
        }
        return list;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
